package bl.auxiliary;

import java.io.Serializable;
import java.util.ArrayList;

import database.factory.BookDataFactory;
import database.factory.BookDataFactoryImpl;
import database.service.BookDataService;

import exception.ItemNotFoundException;

import po.BookPO;
import po.MemberPO;
import po.SaleItemPO;

public class SaleItemList implements Serializable {

	private static final long serialVersionUID = 3266054385812765208L;
	
	private MemberPO memberPO;

	public SaleItemList() {
		memberPO = new MemberPO();
	}

	public SaleItemList(MemberPO memberPO) {
		this.memberPO = memberPO;
	}

	public boolean addItem(SaleItemPO item) {
		ArrayList<SaleItemPO> list = memberPO.getTrolley();
		if (list == null) {
			return false;
		}

		for (int i = 0; i < list.size(); i++) {
			int id = item.getBookID();
			if (id == list.get(i).getBookID()) {
				SaleItemPO addedItem = new SaleItemPO(id, item.getQuantity()
						+ list.get(i).getQuantity());
				list.set(i, addedItem);
				return true;
			}
		}
		list.add(item);
		return true;
	}
	
	public boolean removeItem(int bookID) throws ItemNotFoundException {
		ArrayList<SaleItemPO> list = memberPO.getTrolley();
		if (list == null) {
			return false;
		}
		
		for (int i = 0; i < list.size(); i++) {
			int id = list.get(i).getBookID();
			if (id == bookID) {
				list.remove(i);
				return true;
			}
		}
		
		throw new ItemNotFoundException();
	}
	
	public boolean changeQuantity(int bookID, int quantity) throws ItemNotFoundException {
		ArrayList<SaleItemPO> list = memberPO.getTrolley();
		if (list == null) {
			return false;
		}
		
		for (int i = 0; i < list.size(); i++) {
			int id = list.get(i).getBookID();
			if (id == bookID) {
				SaleItemPO modifiedItem = new SaleItemPO(id, quantity);
				list.set(i, modifiedItem);
				return true;
			}
		}
		
		throw new ItemNotFoundException();
	}

	public double getTotal() {
		ArrayList<SaleItemPO> list = memberPO.getTrolley();
		double total = 0;
		for (int i = 0; i < list.size(); i++) {
			SaleItemPO item = list.get(i);
			int id = item.getBookID();
			BookDataFactory bookDataFactory = new BookDataFactoryImpl();
			BookDataService bookDataService = bookDataFactory.getBookDataService();
			bookDataService.load();
			BookPO book = bookDataService.find(id);
			double eachPrice = book.getPrice() * book.getDiscount();
			total += eachPrice * item.getQuantity();
		}
		return total;
	}

}
